import inquirer from 'inquirer'
import consola from 'consola'
import { greenBright } from 'colorette'
import { join } from 'pathe'
import { Spinner } from 'cli-spinner'
import gitClone from 'git-clone/promise'
import { existsSync, readJson, remove, writeJSON } from 'fs-extra'
import { TEMPLATE_ENUM, GIT_ENUM, TEMPLATE_LIST } from './constant'
import { emptyDir, isEmpty } from './utils'

const { prompt } = inquirer

export const run = async () => {
  const { template } = await prompt({
    name: 'template',
    message: '请选择模板',
    type: 'list',
    default: TEMPLATE_ENUM.web,
    choices: TEMPLATE_LIST
  }) as { template: TEMPLATE_ENUM }

  const { projectName } = await prompt({
    name: 'projectName',
    message: '请输入项目名称',
    type: 'input',
    default: `${template}-template`,
    validate: (val) => {
      const reg = /^[\w-]+$/
      if (!reg.test(val)) {
        consola.error('请输入正确的项目名称')
        return false
      }
      return true
    }
  })

  let appid = ''
  if (template === TEMPLATE_ENUM.weapp) {
    ({ appid } = await prompt({
      name: 'appid',
      message: '请输入appid',
      type: 'input',
      default: '',
    }))
  }

  const targetDir = join(process.cwd(), projectName)

  if (!isEmpty(targetDir)) {
    const { overwrite } = await prompt({
      name: 'overwrite',
      default: true,
      type: 'confirm',
      message: () => (targetDir === '.'
        ? 'Current directory'
        : `Target directory "${targetDir}"`) + ' is not empty, Remove existing files and continue?',
    })
    if (!overwrite) {
      process.exit(1)
    } else {
      emptyDir(targetDir)
    }
  }

  const remote = GIT_ENUM[template]

  const spinner = new Spinner('正在下载中... %s')
  spinner.setSpinnerString('|/-\\')
  spinner.start()

  await gitClone(remote, projectName)

  await remove(join(targetDir, '.git'))

  const packageJson = await readJson(join(targetDir, 'package.json'))
  packageJson.name = projectName

  if (remote === GIT_ENUM.weapp && appid !== '') {
    if (existsSync(join(targetDir, 'project.config.json'))) {
      const miniProjectConfig = await readJson(join(targetDir, 'project.config.json'));
      miniProjectConfig.appid = appid;
      await writeJSON(join(targetDir, 'project.config.json'), miniProjectConfig, { spaces: 2 });
    }
  }

  await writeJSON(join(targetDir, 'package.json'), packageJson, { spaces: 2 })

  spinner.stop(true)

  consola.log(greenBright('模板下载完成'))
}
